//
//  UIImageView+PTSetImage.m
//  PartTimeJob
//
//  Created by 孙锐 on 2017/8/29.
//  Copyright © 2017年 孙锐. All rights reserved.
//

#import "UIImageView+PTSetImage.h"

@implementation UIImageView (PTSetImage)



-(void)SR_setImageWithImageName:(NSString *)name AndPlaceHolderImageName:(NSString *)placeHolder{
    
//    BOOL hasImg = NO;
    if (![name isKindOfClass:[NSNull class]]) {
        if (name == nil || [name isEqualToString:@""] ) {
            self.image = [UIImage imageNamed:placeHolder];
        }else{
            NSString *path_sandox = NSHomeDirectory();
            NSString *path = [path_sandox stringByAppendingPathComponent:@"/Documents/image.plist"];
            NSArray *array = [NSArray arrayWithContentsOfFile:path];
            for (NSDictionary *dict in array) {
                NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:dict];
                NSLog(@"读取成功");
                if([[dictionary allKeys] containsObject:name]){
                    NSData *dataaa = [[NSData alloc]initWithBase64EncodedString:dictionary[name] options:NSDataBase64DecodingIgnoreUnknownCharacters];
                    
                    self.image = [UIImage imageWithData:dataaa];
                    return;
                }else{
                    
                }
            }
            self.image = [UIImage imageNamed:placeHolder];
            
//            [PTWebAgent getImageWithImageName:name success:^(id responseObject) {
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:name]];
                if (data.length == 0 ) {
                    NSLog(@"图片获取有误！");
                    return ;
                }

                NSArray *newArray = [NSArray arrayWithContentsOfFile:path];
                NSString *string = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                NSMutableArray *arr;
                if (newArray != nil) {
                    arr = [[NSMutableArray alloc] initWithArray:newArray];
                }else{
                    arr = [[NSMutableArray alloc]init];
                }
                if (name != nil) {
                    [arr addObject:@{name:string}];
                }
                
                if ([arr writeToFile:path atomically:YES]) {
                    NSLog(@"写入成功");
                };
                
                self.image = [UIImage imageWithData:data];
//            } failure:^(NSError *error) {
//
//            }];
        }

    }else{
        self.image = [UIImage imageNamed:placeHolder];
    }
}

@end

